package com.hu.auth.common.config;

import com.hu.auth.common.exception.CustomException;
import com.hu.auth.common.result.R;
import com.hu.auth.common.result.RCodeEnum;
import com.hu.auth.common.utils.JwtUtil;
import com.hu.auth.common.utils.ResponseUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
public class WebInterceptor extends HandlerInterceptorAdapter {

    private final static ThreadLocal<Map<String, Object>> info = new ThreadLocal<>();

    // 要想使拦截器生效，必须注册到 WebMvcConfigurer 中去
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (!StringUtils.isEmpty(token)) {
            if (JwtUtil.verifyToken(token)) {
                Map<String, Object> map = new HashMap<>();
                map.put("userId", JwtUtil.getUserId(token));
                // map.put("userPerms", JwtUtil.getUserPerms(token));
                info.set(map);
                return true;
            }
            ResponseUtil.out(response, R.fail().message("token不正确，请重新登录"));
            return false;
        }
        // ResponseUtil.out(response, R.fail().message("请求token缺失"));
        throw new CustomException(RCodeEnum.FAIL.getCode(), "请求token缺失");
        // return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 防止内存泄漏的问题
        info.remove();
    }

    public static Long getUserId() {
        return (Long) info.get().get("userId");
    }

    public static String getUserPerms() {
        return info.get().get("userPerms").toString();
    }


}

